import 'dart:convert';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import 'package:flutter/services.dart';
import 'package:webview_flutter/platform_interface.dart';
import 'package:webview_flutter/webview_flutter.dart';

void main() => runApp(const TestJs(title: 'title', url: "www.jianshu.com"));

class TestJs extends StatefulWidget {
  final String title;
  final String url;
  const TestJs({Key? key, required this.title, required this.url})
      : super(key: key);
  @override
  _WebTestState createState() => _WebTestState();
}

class _WebTestState extends State<TestJs> {
  Future<String> _getFile() async {
    return await rootBundle.loadString("https://www.baidu.com/");
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  JavascriptChannel _toasterJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'Toast',
        onMessageReceived: (JavascriptMessage message) {
          print("参数：${message.message}");
          ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text(message.message))
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: widget.title,
        home: Scaffold(
            appBar: AppBar(
              title: Text(widget.title),
            ),
            body: WebView(
              javascriptMode: JavascriptMode.unrestricted, // js执行模式
              javascriptChannels: <JavascriptChannel>[
                // js和flutter通信的channel
                _toasterJavascriptChannel(context)
              ].toSet(),
              initialUrl: "http://192.168.43.145:8081/examples/baselines/", // 初始load的url
              onPageFinished: (String value) {
                print("webview is finish");
                // webview 页面加载调用
              },
            )
        ));
  }
}
